
import React, { useState, useEffect, useImperativeHandle } from 'react'
import useForm from "rc-form-hooks"
import { connect } from 'dva'
import { Form, Input, Select, Button, Table, Radio, DatePicker, message } from 'antd'
import TitleLine from 'components/common/titleLine'
import moment from 'moment'
import { randomString } from 'utils/format'
import './index.styl'

const { Option } = Select

function PrefabricatedProject({ cRef, dispatch, query, getData, deviceCheck: { taskConfAll, detailData } }) {
    const { getFieldDecorator, resetFields } = useForm()

    // 预判信息
    const [hasList, setHasList] = useState(true)
    const [nameOk, setNameOk] = useState(true)
    const [cycleOk, setCycleOk] = useState(true)
    const [cycleTypeOk, setCycleTypeOk] = useState(true)
    const [startTimeOk, setStartTimeOk] = useState(true)
    const [updatePicOk, setUpdatePicOk] = useState(true)
    const [updateVoiceOk, setUpdateVoiceOk] = useState(true)
    const [list, setList] = useState([])
    useEffect(() => {
        dispatch({
            type: 'deviceCheck/checkTaskConfAll',
        })
    }, [dispatch])

    // 预制项目列表

    useEffect(() => {
        if (query.id === undefined) {
            return
        } else if (detailData && detailData.checkTaskVoList) {
            // 添加序号
            const data = []
            detailData.checkTaskVoList.map((item, index) => {
                data.push({
                    ...item,
                    key: randomString(16),
                    serialNumber: index + 1,
                })
            })
            setNameOk(true)
            setHasList(true)
            setCycleOk(true)
            setCycleTypeOk(true)
            setStartTimeOk(true)
            setUpdatePicOk(true)
            setUpdateVoiceOk(true)
            setList(data)
        }
    }, [detailData, detailData.checkTaskVoList, query.id])

    // 输入项目名称
    async function changeName(e, serialNumber) {
        const lists = JSON.parse(JSON.stringify(list))
        lists[serialNumber - 1].name = e.target.value.replace(/\s+/g, '')
        setList(lists)
    }

    // 项目描述
    const changeRemark = (e, serialNumber) => {
        const lists = JSON.parse(JSON.stringify(list))
        lists[serialNumber - 1].remark = e.target.value.replace(/\s+/g, '')
        setList(lists)
    }

    // 项目周期
    const changeCycle = (e, serialNumber) => {
        const lists = JSON.parse(JSON.stringify(list))
        if (!e.target.value) {
            lists[serialNumber - 1].cycle = e.target.value
        }
        if (/^[1-9]\d*$/.test(e.target.value)) {
            lists[serialNumber - 1].cycle = e.target.value
        }
        setList(lists)
    }

    // 项目周期类
    const changeCycleType = (e, serialNumber) => {
        const lists = JSON.parse(JSON.stringify(list))
        lists[serialNumber - 1].cycleType = e.target.value
        setList(lists)
        inspection(lists)
    }

    // 是否上传照片
    const changeUpdatePic = (e, serialNumber) => {
        const lists = JSON.parse(JSON.stringify(list))
        lists[serialNumber - 1].updatePic = e.target.value
        inspection(lists)
        setList(lists)
    }

    // 是否上传声音
    const changeUpdateVoice = (e, serialNumber) => {
        const lists = JSON.parse(JSON.stringify(list))
        lists[serialNumber - 1].updateVoice = e.target.value
        inspection(lists)
        setList(lists)
    }

    // 选择时间
    const changeStartTime = (value, serialNumber) => {
        const lists = JSON.parse(JSON.stringify(list))
        lists[serialNumber - 1].startTime = value
        setList(lists)
        inspection(lists)
    }

    // useEffect(() => {
    //     if (list.length > 0) {
    //         console.log('list',list)
    //         // const isname = list.find(item => item.name === '')
    //         // const iscycleOk = list.find(item => item.cycle === '')
    //         const iscycleTypeOk = list.find(item => item.cycleType === '')
    //         // const isstartTimeOk = list.find(item => item.startTime === '')
    //         const isupdatePicOk = list.find(item => item.updatePic === '')
    //         const isupdateVoiceOk = list.find(item => item.updateVoice === '')
    //         // if (typeof(isname)!= 'undefined') {setNameOk(false)}else{setNameOk(true)}
    //         // if (typeof(iscycleOk)!= 'undefined') {setCycleOk(false)}else{setCycleOk(true)}
    //         if (typeof(iscycleTypeOk)!= 'undefined') {setCycleTypeOk(false)}else{setCycleTypeOk(true)}
    //         // if (typeof(isstartTimeOk)!= 'undefined') {setStartTimeOk(false)}else{setStartTimeOk(true)}
    //         if (typeof(isupdatePicOk)!= 'undefined') {setUpdatePicOk(false)}else{setUpdatePicOk(true)}
    //         if (typeof(isupdateVoiceOk)!= 'undefined') {setUpdateVoiceOk(false)}else{setUpdateVoiceOk(true)}
    //     }
    // },[list])

    const inspection = (lists) => {
        if (lists.length > 0) {
            const isname = lists.find(item => item.name === '')
            const iscycleOk = lists.find(item => item.cycle === '')
            const iscycleTypeOk = lists.find(item => item.cycleType === '')
            const isstartTimeOk = lists.find(item => item.startTime === '')
            const isupdatePicOk = lists.find(item => item.updatePic === '')
            const isupdateVoiceOk = lists.find(item => item.updateVoice === '')

            if (typeof (isname) != 'undefined') { setNameOk(false) } else { setNameOk(true) }
            if (typeof (iscycleOk) != 'undefined') { setCycleOk(false) } else { setCycleOk(true) }
            if (typeof (iscycleTypeOk) != 'undefined') { setCycleTypeOk(false) } else { setCycleTypeOk(true) }
            if (typeof (isstartTimeOk) != 'undefined') { setStartTimeOk(false) } else { setStartTimeOk(true) }
            if (typeof (isupdatePicOk) != 'undefined') { setUpdatePicOk(false) } else { setUpdatePicOk(true) }
            if (typeof (isupdateVoiceOk) != 'undefined') { setUpdateVoiceOk(false) } else { setUpdateVoiceOk(true) }
            if (
                typeof (isname) != 'undefined'
                || typeof (iscycleOk) != 'undefined'
                || typeof (iscycleTypeOk) != 'undefined'
                || typeof (isstartTimeOk) != 'undefined'
                || typeof (isupdatePicOk) != 'undefined'
                || typeof (isupdateVoiceOk) != 'undefined'
            ) {
                return true
            }
            return false
        } else {
            setHasList(false)
        }
    }

    const submitData = () => {
        const isOk = inspection(list)
        if (!isOk) {
            getData(list, 'list')
            return
        }
        getData([], 'list')
    }

    useImperativeHandle(cRef, () => ({
        submitData
    }));

    // 当天的时间日期之前的不可选
    function disabledDate(current) {
        return current && current < moment().subtract(1, 'day');
    }

    // 失去焦点校验
    const nameValue = () => {
        inspection(list)
    }
    // 选择项目日期关闭的校验提示
    function handleOnOpenChange(open) {
        if (!open) {
            inspection(list)
        }
    }
    const columns = [
        {
            title: '序号',
            dataIndex: 'serialNumber',
            key: 'serialNumber',
            align: 'center',
            width: '0.8rem'
        },
        {
            title: '项目名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
            render: (text, record) => {
                return (
                    <div className="hasErrTip">
                        <Input
                            style={{width: '90%'}}
                            className={['self-input', text === '' ? 'err-border' : ''].join(' ')}
                            maxLength={20}
                            value={record.name}
                            placeholder="请输入"
                            onChange={(e) => changeName(e, record.serialNumber)}
                            onBlur={nameValue}
                        />
                    </div>
                )
            }
        },
        {
            title: '项目描述',
            dataIndex: 'remark',
            key: 'remark',
            align: 'center',
            render: (text, record) => (
                <Input
                    style={{width: '90%'}}
                    className="self-input"
                    value={text}
                    placeholder="请输入"
                    maxLength={20}
                    onChange={(e) => changeRemark(e, record.serialNumber)}
                />
            )
        },
        {
            title: '项目周期',
            dataIndex: 'cycle',
            key: 'cycle',
            align: 'center',
            className: 'item_zq',
            width: '185px',
            render: (text, record) => (
                <div style={{ overflow: 'hidden', width: '180px'}}>
                    <div className="hasErrTip" style={{ float: 'left', width: '65px',marginRight: '2px'}}>
                        <Input
                            className={['self-input', (text !== '' && record.cycleType !== '' && /^[1-9]\d*$/.test(text) && (text <= 999)) ? '' : 'err-border'].join(' ')}
                            placeholder="请输入"
                            value={record.cycle}
                            onChange={(e) => changeCycle(e, record.serialNumber)}
                            maxLength={3}
                            onBlur={nameValue}
                        />
                    </div>
                    <Radio.Group style={{ float: 'right', width:'110px', textAlign: 'right'}} value={record.cycleType + ''} className="period-radio" onChange={(e) => changeCycleType(e, record.serialNumber)}>
                        <Radio.Button style={{textAlign: 'center'}} value="1">天</Radio.Button>
                        <Radio.Button style={{textAlign: 'center'}} value="2">周</Radio.Button>
                        <Radio.Button style={{textAlign: 'center'}} value="3">月</Radio.Button>
                    </Radio.Group>
                </div>
            )
        },
        {
            title: '开始时间',
            dataIndex: 'startTime',
            key: 'startTime',
            width: '150px',
            align: 'center',
            render: (text, record) => (
                <div>
                    <DatePicker
                        style={{width: '90%'}}
                        allowClear={false}
                        onOpenChange={handleOnOpenChange}
                        disabledDate={disabledDate}
                        className={['self-date', text === '' ? 'err-border' : ''].join(' ')}
                        showToday={false}
                        placeholder="请选择时间"
                        value={text === '' ? null : moment(text)}
                        onChange={(e, str) => changeStartTime(str, record.serialNumber)}
                    />
                </div>
            )
        },
        {
            title: '是否上传照片',
            dataIndex: 'updatePic',
            key: 'updatePic',
            align: 'center',
            width: '150px',
            render: (text, record) => (
                <span>
                    <Radio.Group
                        onChange={(e) => changeUpdatePic(e, record.serialNumber)}
                        value={text}
                    >
                        <Radio value={1} style={{ color: text !== '' ? '' : '#f40' }}>是</Radio>
                        <Radio value={0} style={{ color: text !== '' ? '' : '#f40' }}>否</Radio>
                    </Radio.Group>
                </span>
            )
        },
        {
            title: '是否上传噪音',
            dataIndex: 'updateVoice',
            key: 'updateVoice',
            align: 'center',
            width: '150px',
            render: (text, record) => (
                <>
                    <Radio.Group
                        onChange={(e) => changeUpdateVoice(e, record.serialNumber)}
                        value={text}
                        onBlur={nameValue}
                    >
                        <Radio value={1} style={{ color: text !== '' ? '' : '#f40' }}>是</Radio>
                        <Radio value={0} style={{ color: text !== '' ? '' : '#f40' }}>否</Radio>
                    </Radio.Group>
                </>
            )
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            align: 'center',
            width: '2rem',
            render: (text, record) => (
                <span className="td-blue" style={{ margin: '0' }} onClick={() => handleDelete(record)}>删除</span>
            ),
        },
    ]

    // 选择预置项目
    const handleSelectPresetProject = (value, e) => {
        setHasList(true)
        const newList = list
        if (newList.length >= 30) {
            message.warning('最多只能添加30项！')
            return
        }

        const data = taskConfAll.find(item => {
            if (item.id === value) {
                if (newList.length === 0) {
                    item['startTime'] = ''
                    return item
                }
                item['startTime'] = item.id === value ? newList[newList.length - 1].startTime : item.startTime
                return item
            }
        })
        data['new'] = true
        newList.push(data)

        setList(newList.map((item, index) => {
            return {
                ...item,
                startTime: newList.length !== 0 && newList[newList.length - 1].startTime && item.id === value ? newList[newList.length - 1].startTime : item.startTime,
                serialNumber: index + 1,
                key: randomString(16),
            }
        }))
    }

    // 配置自定义项目
    const selObject = () => {
        setHasList(true)
        const newLists = JSON.parse(JSON.stringify(list))
        if (newLists.length >= 30) {
            message.warning('最多只能添加30项！')
            return
        }
        newLists.push({
            name: "",
            updateVoice: '',
            updatePic: '',
            cycle: '',
            cycleType: '',
            // startTime: newLists.length !== 0 ? newLists[newLists.length - 1].startTime : '',
            startTime: newLists.length !== 0 && newLists[newLists.length - 1].startTime ? newLists[newLists.length - 1].startTime : '',
            remark: '',
            key: randomString(16),
            serialNumber: newLists.length > 0 ? newLists[newLists.length - 1].serialNumber + 1 : 1,
        })
        setList(newLists)
    }

    // 删除预置项目
    const handleDelete = (record) => {
        const newList = list.filter(item => item.key !== record.key).map((it, index) => {
            return {
                ...it,
                key: randomString(16),
                serialNumber: index + 1
            }
        })
        if (newList.length === 0) {
            setNameOk(true)
            setHasList(true)
            setCycleOk(true)
            setCycleTypeOk(true)
            setStartTimeOk(true)
            setUpdatePicOk(true)
            setUpdateVoiceOk(true)
            resetFields()
        }

        setList(list.filter(item => item.key !== record.key).map((it, index) => {
            return {
                ...it,
                key: randomString(16),
                serialNumber: index + 1
            }
        }))
    }

    const layout = {
        labelCol: { span: 9 },
        wrapperCol: { span: 15 },
    };
    console.log('randomString(16)', randomString(16))

    return (
        <div className="prefabricatedProject">
            <div className="table-header">
                <TitleLine title="配置点检项目"></TitleLine>
                <div className="presetProject">
                    <Form.Item label="选择预置项目" {...layout} colon={false}>
                        {getFieldDecorator('presetProject', {
                            rules: [{ required: true, message: '请选择预置项目' }],
                        })(
                            <Select
                                placeholder="请选择"
                                className="self-select"
                                onSelect={handleSelectPresetProject}
                                style={{ height: '36px', width: '2.38rem' }}
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                            >
                                {
                                    taskConfAll && taskConfAll.length && taskConfAll.map((item) => {
                                        return (
                                            <Option value={item.id} key={item.id}>{item.name}</Option>
                                        )
                                    })
                                }

                            </Select>
                        )}
                    </Form.Item>
                    <Button className="white-button" onClick={selObject}>添加自定义项目</Button>
                    <span className="tip">最多可添加30个点检项目</span>
                </div>
            </div>
            <Table
                columns={columns}
                dataSource={list}
                pagination={false}
                className="self-table"
                bordered={true}
            />

            <div className="table-tip" id='nodata_error'>
                <span style={{display: 'block'}} >{!hasList ? '请配置点检项目 /' + ' ' : ''}</span>
                <span>{nameOk ? '' : '请填写项目名称 /' + ' '}</span>
                <span>{cycleOk && cycleTypeOk ? '' : '请选择项目周期 /' + ' '}</span>
                <span>{startTimeOk ? '' : '请选择开始时间 /' + ' '}</span>
                <span>{updatePicOk ? '' : '请选择是否上传图片 /' + ' '}</span>
                <span>{updateVoiceOk ? '' : '请选择是否上传噪音'}</span>
            </div>
        </div>
    )
}


export default connect(({ deviceCheck }) => ({
    deviceCheck
}))(PrefabricatedProject)
